package com.com.exce;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.Properties;

/**
 * @Author WaveHi
 * @Date 24/8/2021 下午 2:43
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
public class PropertiesTest {

    @Test
    public void test1() throws Exception {

        //获取配置文件
        File proFile = new File("resources/BaseDaoImpl.properties");

        //获取流读取配置文件
        FileInputStream fis = new FileInputStream(proFile);

        //获取属性值
        Properties properties = new Properties();

        //加载配置文件
        properties.load(fis);

        //读取数据
        System.out.println(properties.getProperty("username"));
        System.out.println(properties.getProperty("age"));


    }

    @Test
    public void test2() throws IOException {


        //获取类的加载器
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        //加载配置文件的字节码文件
        InputStream ras = classLoader.getResourceAsStream("BaseDaoImpl.properties");

        //获取属性集
        Properties ps = new Properties();

        //加载配置文件到属性集中
        ps.load(ras);

        //读取数据
        System.out.println(ps.getProperty("username"));
        System.out.println(ps.getProperty("age"));


    }

    @Test
    public void test3() throws ParserConfigurationException, IOException, SAXException {

        //获取xml文件
        File file = new File("resources/BaseDaoImpl.xml");

        //测试DocumentBuilderFactory类
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        //测试DocumentBuilder
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        //解析配置文件
        Document doc = documentBuilder.parse(file);

        //获取根标签
        Element documentElement = doc.getDocumentElement();

        //获取标签列表
        NodeList name = documentElement.getElementsByTagName("name");

        //获取节点
        Node item = name.item(0);
        int length = name.getLength();

        //获取节点文本内容
        System.out.println(item.getTextContent());

        //设置节点文本内容
        item.setTextContent("Wow!");
        System.out.println(item.getTextContent());


    }

}
